package net.fei.scan.quick

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.ContactsContract
import android.provider.MediaStore
import android.provider.Settings
import android.util.Log
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.zxing.BinaryBitmap
import com.google.zxing.DecodeHintType
import com.google.zxing.RGBLuminanceSource
import com.google.zxing.common.HybridBinarizer
import com.google.zxing.integration.android.IntentIntegrator
import com.google.zxing.qrcode.QRCodeReader
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import net.fei.scan.quick.adapter.MainAdapter
import net.fei.scan.quick.databinding.ActivityMainBinding
import net.fei.scan.quick.db.DbUtils
import net.fei.scan.quick.entity.History
import net.fei.scan.quick.ui.CreateActivity
import net.fei.scan.quick.ui.HistoryActivity
import net.fei.scan.quick.ui.UserORActivity
import net.fei.scan.quick.util.CameraLayout
import java.util.EnumMap
import java.util.regex.Matcher
import java.util.regex.Pattern


class MainActivity : AppCompatActivity() {
    private lateinit var bin: ActivityMainBinding
    private lateinit var galleryLauncher: ActivityResultLauncher<Intent>

    private lateinit var list: MutableList<History>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        bin = ActivityMainBinding.inflate(layoutInflater)
        setContentView(bin.root)
        initPermission()
        initLauncher()
        loadDatabase()

        bin.image.setOnClickListener {
            val galleryIntent =
                Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
            galleryLauncher.launch(galleryIntent)
        }

        bin.btn.setOnClickListener {
            val intentIntegrator = IntentIntegrator(this)
            intentIntegrator.captureActivity = CameraLayout::class.java
            intentIntegrator.apply {
                setPrompt("")
                initiateScan()
            }
        }
        bin.create.setOnClickListener {
            jumpInterface(CreateActivity::class.java)
        }
        bin.userOR.setOnClickListener {
            jumpInterface(UserORActivity::class.java)
        }
        bin.history.setOnClickListener {
            jumpInterface(HistoryActivity::class.java)
        }
    }

    private fun loadDatabase() {
        list = DbUtils(this).getAllData(0) as MutableList<History>
        bin.rcv.apply {
            adapter = MainAdapter(list, this@MainActivity)
            layoutManager =
                LinearLayoutManager(this@MainActivity, LinearLayoutManager.VERTICAL, false)
        }
    }

    private fun jumpInterface(activity: Class<*>) {
        startActivity(Intent(this@MainActivity, activity))
    }

    override fun onRestart() {
        super.onRestart()
        loadDatabase()
    }

    private fun initLauncher() {
        galleryLauncher =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
                val data: Uri? = result.data?.data
                if (data != null) {
                    val imagePath = getRealPathFromUri(this, data)
                    val decodeFile = BitmapFactory.decodeFile(imagePath)
                    val result = setZxingResult(decodeFile)
                    handleScanResult(result.toString())
                }
            }
    }

    private fun getRealPathFromUri(context: Context, uri: Uri): String? {
        val projection = arrayOf(MediaStore.Images.Media.DATA)
        val cursor: Cursor? = context.contentResolver.query(uri, projection, null, null, null)
        return cursor?.use {
            val columnIndex = it.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
            it.moveToFirst()
            it.getString(columnIndex)
        }
    }

    private fun setZxingResult(bitmap: Bitmap): com.google.zxing.Result {
        val picWidth = bitmap.width
        val picHeight = bitmap.height
        val pix = IntArray(picWidth * picHeight)
        bitmap.getPixels(pix, 0, picWidth, 0, 0, picWidth, picHeight)
        val rgbLuminanceSource = RGBLuminanceSource(picWidth, picHeight, pix)
        val bb = BinaryBitmap(HybridBinarizer(rgbLuminanceSource))
        val qrCodeReader = QRCodeReader()
        val hints: MutableMap<DecodeHintType, Any?> = EnumMap(DecodeHintType::class.java)
        hints[DecodeHintType.CHARACTER_SET] = "utf-8"
        hints[DecodeHintType.TRY_HARDER] = true
        return qrCodeReader.decode(bb, hints)
    }


    private fun initPermission() {
        XXPermissions.with(this).permission(Permission.CAMERA)
            .permission(Permission.READ_MEDIA_IMAGES).request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, allow: Boolean) {
                    if (allow) {
                        return
                    }
                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    if (doNotAskAgain) {
                        XXPermissions.startPermissionActivity(this@MainActivity, permissions)
                    }
                }
            })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (result.contents != null) {
                val contents = result.contents
                handleScanResult(contents.toString())
                Log.d("TAG", "$contents")
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
        super.onActivityResult(requestCode, resultCode, data)
    }

    private fun handleScanResult(contents: String) { // 在这里根据扫描结果的内容执行相应的操作

        // 示例：如果是网址，打开浏览器
        if (contents.startsWith("http://") || contents.startsWith("https://")) {
            val intent = Intent(Intent.ACTION_VIEW, android.net.Uri.parse(contents))
            startActivity(intent)
        }

        // 示例：如果是电话号码，拨打电话
        if (contents.startsWith("tel:")) {
            val intent = Intent(Intent.ACTION_DIAL, android.net.Uri.parse(contents))
            startActivity(intent)
        }

        // 示例：如果是短信内容，发送短信
        if (contents.startsWith("sms:")) {
            val intent = Intent(Intent.ACTION_SENDTO, android.net.Uri.parse(contents))
            startActivity(intent)
        }
        if (contents.startsWith("WIFI:")) {
            val wifiPassword: String = extractPasswordFromWifiInfo(contents).toString()
            copyToClipboard(this,wifiPassword)
            openWiFiSettings()
        }
        if (contents.startsWith("BEGIN:VCARD")) {
            val name = parseVCardField(contents, "N")
            val phone = parseVCardField(contents, "TEL")
            val email = parseVCardField(contents, "EMAIL")
            val intent = Intent(ContactsContract.Intents.Insert.ACTION)
            intent.type = ContactsContract.RawContacts.CONTENT_TYPE
            intent.putExtra(ContactsContract.Intents.Insert.NAME, name)
            intent.putExtra(ContactsContract.Intents.Insert.PHONE, phone)
            intent.putExtra(ContactsContract.Intents.Insert.EMAIL, email)
            startActivity(intent)
        }
        if (contents.startsWith("mailto:")) {
            val emailAddress = parseEmail("contents")
            val subject = parseEmailField(contents, "subject")
            val body = parseEmailField(contents, "body")

            val emailIntent = Intent(Intent.ACTION_SENDTO)
            emailIntent.data = Uri.parse("mailto:$emailAddress")
            emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject)
            emailIntent.putExtra(Intent.EXTRA_TEXT, body)
            startActivity(Intent.createChooser(emailIntent, getString(R.string.lkhvdflkhv)))
        }else{
            copyToClipboard(this,contents)
        }

    }
    private fun parseEmail(emailData: String): String {
        val startIndex = emailData.indexOf("mailto:")
        if (startIndex != -1) {
            val endIndex = emailData.indexOf('?')
            return if (endIndex != -1) {
                emailData.substring(startIndex + "mailto:".length, endIndex)
            } else {
                emailData.substring(startIndex + "mailto:".length)
            }
        }
        return ""
    }

    private fun parseEmailField(emailData: String, fieldName: String): String {
        val start = emailData.indexOf("$fieldName=")
        if (start == -1) {
            return ""
        }

        val end = emailData.indexOf('&', start)
        val value = if (end != -1) {
            emailData.substring(start + fieldName.length + 1, end)
        } else {
            emailData.substring(start + fieldName.length + 1)
        }

        return Uri.decode(value)
    }

    private fun openWiFiSettings() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val panelIntent = Intent(Settings.ACTION_WIFI_SETTINGS)
            startActivity(panelIntent)
        } else {
            val intent = Intent(Settings.ACTION_WIRELESS_SETTINGS)
            startActivity(intent)
        }
    }

    private fun extractPasswordFromWifiInfo(wifiInfo: String): String? { // 使用正则表达式提取密码
        val pattern = "P:([^;]+);"
        val r: Pattern = Pattern.compile(pattern)
        val m: Matcher = r.matcher(wifiInfo)
        return if (m.find()) {
            m.group(1)
        } else {
            null
        }
    }
    private fun copyToClipboard(context: Context, text: String, label: String = "Copied Text") {
        val clipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        val clipData = ClipData.newPlainText(label, text)
        clipboardManager.setPrimaryClip(clipData)
        Toast.makeText(context, getString(R.string.dfskjvbdlfskbv), Toast.LENGTH_SHORT).show()
    }
    private fun parseVCardField(vCardData: String, field: String): String? {
        val vCardLines =
            vCardData.split("\n".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
        for (line in vCardLines) {
            val parts = line.split(":".toRegex(), limit = 2).toTypedArray()
            if (parts.size == 2) {
                val key = parts[0].trim { it <= ' ' }
                val value = parts[1].trim { it <= ' ' }

                // 查找对应字段的值
                if (field == key) {
                    return value
                }
            }
        }
        return null
    }
}